package com.my.study.service;

import com.my.study.common.ClientConnectServerThread;
import com.my.study.common.message.Message;
import com.my.study.common.message.MessageType;
import com.my.study.common.message.User;
import com.my.study.manage.ManageClientConnectServerThread;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @author Carlos
 * @version 1.0
 * @Description 用户注册/登录实现类
 * @date 2021/7/18 10:45
 **/
public class UserClientService {

    private User user = new User();

    private Socket socket;

    public boolean checkUser(String userId, String pwd) {
        boolean isPassCheckUser = false;

        user.setUserId(userId);
        user.setPwd(pwd);

        // socket操作
        try {
            socket = new Socket(InetAddress.getLocalHost(), 9999);
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            // 发送
            oos.writeObject(user);

            // 从服务器读取
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            Message message = (Message) ois.readObject();

            if (MessageType.MESSAGE_LOGIN_SUCCEED.equals(message.getMsgType())) {
                // 创建一个和服务器保持通信的线程类
                ClientConnectServerThread ccst = new ClientConnectServerThread(socket);
                // 启动线程
                ccst.start();
                // 添加到管理线程中
                ManageClientConnectServerThread.addClientConnectServerThread(userId, ccst);
                isPassCheckUser = true;
            }
            // 如果登录失败
            else {
                // 关闭socket
                socket.close();
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        return isPassCheckUser;
    }

}
